package com.example.gitclient.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.gitclient.model.Repository;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 仓库管理器，用于保存和加载仓库信息
 */
public class RepositoryManager {
    private static final String PREFS_NAME = "GitClientPrefs";
    private static final String KEY_REPOSITORIES = "repositories";

    private final SharedPreferences sharedPreferences;

    /**
     * 创建仓库管理器
     * @param context 上下文
     */
    public RepositoryManager(Context context) {
        this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }

    /**
     * 获取所有仓库
     * @return 仓库列表
     */
    public List<Repository> getRepositories() {
        List<Repository> repositories = new ArrayList<>();
        String json = sharedPreferences.getString(KEY_REPOSITORIES, null);

        if (json != null) {
            try {
                JSONArray jsonArray = new JSONArray(json);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String name = jsonObject.getString("name");
                    String path = jsonObject.getString("path");
                    String remoteUrl = jsonObject.has("remoteUrl") ? jsonObject.getString("remoteUrl") : null;

                    // 检查仓库目录是否存在
                    File repoDir = new File(path);
                    if (repoDir.exists() && new File(repoDir, ".git").exists()) {
                        Repository repository = new Repository(name, path);
                        if (remoteUrl != null) {
                            repository.setRemoteUrl(remoteUrl);
                        }
                        repositories.add(repository);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return repositories;
    }

    /**
     * 保存仓库
     * @param repository 仓库信息
     */
    public void saveRepository(Repository repository) {
        List<Repository> repositories = getRepositories();
        
        // 检查是否已存在相同路径的仓库
        boolean exists = false;
        for (int i = 0; i < repositories.size(); i++) {
            if (repositories.get(i).getPath().equals(repository.getPath())) {
                repositories.set(i, repository);
                exists = true;
                break;
            }
        }
        
        // 如果不存在，添加到列表
        if (!exists) {
            repositories.add(repository);
        }
        
        saveRepositories(repositories);
    }

    /**
     * 删除仓库
     * @param repository 仓库信息
     */
    public void deleteRepository(Repository repository) {
        List<Repository> repositories = getRepositories();
        
        // 查找并删除仓库
        for (int i = 0; i < repositories.size(); i++) {
            if (repositories.get(i).getPath().equals(repository.getPath())) {
                repositories.remove(i);
                break;
            }
        }
        
        saveRepositories(repositories);
    }

    /**
     * 保存所有仓库
     * @param repositories 仓库列表
     */
    private void saveRepositories(List<Repository> repositories) {
        try {
            JSONArray jsonArray = new JSONArray();
            for (Repository repository : repositories) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", repository.getName());
                jsonObject.put("path", repository.getPath());
                if (repository.getRemoteUrl() != null) {
                    jsonObject.put("remoteUrl", repository.getRemoteUrl());
                }
                jsonArray.put(jsonObject);
            }
            
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(KEY_REPOSITORIES, jsonArray.toString());
            editor.apply();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}